package main

import (
	"fmt"
	"net"
	"path/filepath"
	"runtime"

	"testrpc/biz/middleware"
	"testrpc/conf"

	"github.com/cloudwego/kitex/pkg/klog"
	"github.com/cloudwego/kitex/pkg/rpcinfo"
	"github.com/cloudwego/kitex/pkg/transmeta"
	"github.com/cloudwego/kitex/server"
	"github.com/grayscalecloud/kitexcommon/mtl"
	"github.com/grayscalecloud/kitexcommon/serversuite"
	"gopkg.in/natefinch/lumberjack.v2"
)

var projectRoot string

func init() {
	_, file, _, ok := runtime.Caller(0)
	if !ok {
		projectRoot = ""
		return
	}
	// 获取base包所在目录的父目录作为项目根目录
	projectRoot = filepath.Dir(file)
	fmt.Println("-- 根目录：", projectRoot)
}

func main() {
	opts := kitexInit()

	svr := server.NewServer(opts...)
	// 注册服务
	RegisterService(svr)

	err := svr.Run()
	if err != nil {
		klog.Error(err.Error())
	}
}

func kitexInit() (opts []server.Option) {
	// address
	addr, err := net.ResolveTCPAddr("tcp", conf.GetConf().Kitex.Address)
	if err != nil {
		panic(err)
	}
	opts = append(opts, server.WithServiceAddr(addr))

	// service info
	opts = append(opts, server.WithServerBasicInfo(&rpcinfo.EndpointBasicInfo{
		ServiceName: conf.GetConf().Kitex.Service,
	}))
	// thrift meta handler
	opts = append(opts, server.WithMetaHandler(transmeta.ServerTTHeaderHandler))

	// 添加上下文处理中间件
	opts = append(opts, server.WithMiddleware(middleware.ContextMiddleware()))
	// 服务发现
	opts = append(opts, server.WithSuite(serversuite.ConsulServerSuite{
		CurrentServiceName: conf.GetConf().Kitex.Service,
		RegistryAddr:       conf.GetConf().Registry.RegistryAddress,
		OtelEndpoint:       conf.GetConf().OTel.Endpoint,
		EnableMetrics:      conf.GetConf().OTel.EnableMetrics,
		EnableTracing:      conf.GetConf().OTel.EnableTracing,
	}))
	// Klog 设置
	mtl.InitLog(&lumberjack.Logger{
		Filename:   conf.GetConf().Kitex.LogFileName,
		MaxSize:    conf.GetConf().Kitex.LogMaxSize,
		MaxBackups: conf.GetConf().Kitex.LogMaxBackups,
		MaxAge:     conf.GetConf().Kitex.LogMaxAge,
	}, projectRoot, conf.GetConf().OTel.EnableTracing)
	return
}
